package com.atguigu.gulimall.product.service.impl;

import com.fasterxml.jackson.databind.introspect.AnnotationCollector;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        // 2.组装成父子树型结构
        return categoryEntities.stream().filter(categoryEntity ->
                        categoryEntity.getParentCid() == 0
                ).peek(menu -> menu.setChildren(getChildrens(menu, categoryEntities)))
                .sorted(Comparator.comparingInt(CategoryEntity::getSort))
                .collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(Long[] catIds) {
        // TODO 检查删除菜单,都否被引用
        // 逻辑删除
        baseMapper.deleteBatchIds(Arrays.asList(catIds));
    }

    @Override
    public Long[] getCatelogPath(Long catelogId) {
        List<Long> catelogPath = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, catelogPath);
        Collections.reverse(parentPath);
        System.out.println(parentPath);
        return parentPath.toArray(new Long[0]);
    }


    private List<Long> findParentPath(Long catelogId, List<Long> catelogPath) {
        catelogPath.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            findParentPath(categoryEntity.getParentCid(), catelogPath);
        }
        return catelogPath;
    }

    // 递归查询子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity current, List<CategoryEntity> all) {
        return all.stream().filter(categoryEntity ->
                        categoryEntity.getParentCid().equals(current.getCatId()))
                .peek(menu -> menu.setChildren(getChildrens(menu, all)))
                .sorted(Comparator.comparingInt(CategoryEntity::getSort))
                .collect(Collectors.toList());
    }

}